#include "pool_head.h"

void print_progress_bar(size_t total_received,size_t file_size){
    int width = 50;  // 进度条宽度
    float progress = (float)total_received / file_size;
    int pos = width * progress;

    printf("\r[");
    for (int i = 0; i < width; ++i) {
        if (i < pos) printf("=");
        else if (i == pos) printf(">");
        else printf(" ");
    }
    printf("] %5.2f%%", (progress * 100));
    usleep(1000);
    fflush(stdout);
}

int download_file(int client_fd, char *file_name){
    //打开对应的文件
    int file_fd = open(file_name,O_RDONLY);
    ERROR_CHECK(file_fd,-1,"open");
    struct stat file_detail;
    fstat(file_fd,&file_detail);
    
    //把文件大小传给客户端
    send(client_fd,&file_detail.st_size,sizeof(off_t),MSG_NOSIGNAL);
    //直接将文件发送给客户端
    sendfile(client_fd,file_fd,NULL,file_detail.st_size);
    close(client_fd);
    return 0;
}

int upload_file(int client_fd, char *file_name){
    int file_fd = open(file_name,O_RDWR | O_CREAT,0666);
    ERROR_CHECK(file_fd,-1,"open");

    off_t file_size = 0;
    //接收文件的大小
    recv(client_fd,&file_size,sizeof(off_t),MSG_WAITALL);
    printf("file_size : %ld \n",file_size);
    ftruncate(file_fd,file_size);

    //做文件映射
    void *p = mmap(NULL,file_size,PROT_READ | PROT_WRITE,MAP_SHARED,file_fd,0);

    size_t recveied_total = 0; //已读取的字节数
    size_t chunk_size = 1024; //每次读取的字节数
    while(recveied_total < file_size){
        //计算当前应该读取的字节数
        size_t cur_read_size = (file_size - recveied_total) < chunk_size ? (file_size - recveied_total) : chunk_size;
        size_t read_size = recv(client_fd,p+recveied_total,cur_read_size,MSG_WAITALL);
        if(read_size == 0){
            //发送方关闭连接且无数据可读
            break;
        }
        recveied_total += read_size;
        print_progress_bar(recveied_total,file_size);
    }
    printf("\n");
    munmap(p,file_size);
    
    data_s msg;
    memset(&msg,0,sizeof(msg));
    char *message = "upload sucess...";
    msg.len = strlen(message);
    memcpy(msg.buf,message,msg.len);
    send(client_fd,&msg,sizeof(int) + msg.len,MSG_NOSIGNAL);
    close(file_fd);
    return 0;
}